package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.consts.Const;
import com.example.demo.dto.PoetryListDTO;
import com.example.demo.entity.Author;
import com.example.demo.entity.Poetry;
import com.example.demo.mapper.PoetryMapper;
import com.example.demo.param.QueryParam;
import com.example.demo.service.PoetryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class PoetryServiceImpl implements PoetryService {

    @Resource
    private PoetryMapper poetryMapper;

    @Override
    public Poetry getRandomPoetry() {
        /*获取一个随机 maxSize以内的 随机值*/
        List<Integer> list = generateRandomId(1);
        return poetryMapper.selectById(list.get(0));
    }

    @Override
    public Poetry getPoetryById(Integer id) {
        return poetryMapper.selectById(id);
    }

    @Override
    public List<Poetry> getPoetrySelectively(QueryParam queryParam) {
        QueryWrapper<Poetry> wrapper = new QueryWrapper();
        String author = queryParam.getAuthor();
        String dynasty = queryParam.getDynasty();
        String kindCn = queryParam.getKindCn();
        wrapper.eq(author != null && author != "","author",author)
                .eq(dynasty != null && dynasty != "","dynasty",dynasty)
                .eq(kindCn != null && kindCn != "","kind_cn",kindCn);
        Page<Poetry> page = new Page<>(queryParam.getPageNo(), Const.PAGE_SIZE);
        IPage<Poetry> userIPage = poetryMapper.selectPage(page, wrapper);
        return userIPage.getRecords();
    }

    @Override
    public List<Poetry> getRandomPoetryPage(Integer pageNo) {
        QueryWrapper<Poetry> wrapper = new QueryWrapper();
        //随机生成 10个id去查库
        List<Integer> list = generateRandomId(Const.PAGE_SIZE);
        wrapper.in("id",list).orderByAsc("id");
        Page<Poetry> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Poetry> userIPage = poetryMapper.selectPage(page, wrapper);
        return userIPage.getRecords();
    }

    @Override
    public List<Poetry> getPoetryByContent(String content,Integer pageNo) {
        QueryWrapper<Poetry> wrapper = new QueryWrapper();
        wrapper.like("content",content);
        Page<Poetry> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Poetry> userIPage = poetryMapper.selectPage(page, wrapper);
        return userIPage.getRecords();
    }

    //随机生成n个id
    private List<Integer> generateRandomId(Integer count){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            list.add((int)(Const.POETRY_MIN_SIZE+Math.random()*(Const.POETRY_MAX_IZE-Const.POETRY_MIN_SIZE+1)));
        }
        return list;
    }

}
